package com.mao.crowd.controller;

import com.mao.crowd.api.MySQLRemoteService;
import com.mao.crowd.config.OSSProperties;
import com.mao.crowd.constant.CrowdConstant;
import com.mao.crowd.entity.vo.*;
import com.mao.crowd.util.CrowdUtil;
import com.mao.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.awt.ModalityListener;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Controller
public class ProjectConsumerController {

    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;

    @RequestMapping("/get/project/detail/{projectId}")
    public String getProjectDetail(@PathVariable("projectId") Integer projectId, Model model){

        ResultEntity<DetailProjectVO> resultEntity = mySQLRemoteService.getDetailProjectVORemote(projectId);

        String result = resultEntity.getResult();
        if (ResultEntity.SUCCESS.equals(result)){
            DetailProjectVO detailProjectVO = resultEntity.getData();
            model.addAttribute(CrowdConstant.ATTR_NAME_PROJECT_DETAIL,detailProjectVO);
        }
        return "project-show-detail";
    }



    /**
     * 提交projectVO对象
     * @param session 从session中取出临时projectVO对象
     * @param memberConfirmInfoVO 页面提交的确认信息
     * @return
     */
    @RequestMapping("/create/confirm")
    public String saveConfirm(HttpSession session, MemberConfirmInfoVO memberConfirmInfoVO,ModelMap modelMap){

        // 读取临时存储的projectVO对象
        ProjectVO projectVO = (ProjectVO)session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

        if (projectVO == null){
            throw new RuntimeException(CrowdConstant.MESSAGE_TEMPLE_PROJECT_EMPTY);
        }

        // 确认信息存入proectVO对象
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);

        MemberLoginVO memberLoginVO = (MemberLoginVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);

        Integer memberId = memberLoginVO.getId();
        // 保存全部项目信息到mySQL
        ResultEntity<String> saveResultEntity = mySQLRemoteService.saveProjectVORemote(projectVO,memberId);

        if (ResultEntity.FAILED.equals(saveResultEntity.getResult())){
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,saveResultEntity.getMessage());
            return "project-confirm";
        }

        // 从session中移除临时projectVO
        session.removeAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

        return "redirect:http://localhost/create/success";
    }

    @ResponseBody
    @RequestMapping("/create/save/return.json")
    public ResultEntity<String> saveReturn(ReturnVO returnVO,HttpSession session){

        try {
            // 读取session域中的projectVO对象
            ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
            if (projectVO == null){
                return ResultEntity.failed(CrowdConstant.MESSAGE_TEMPLE_PROJECT_EMPTY);
            }
            // 把回报信息存入projectVO中的回报信息集合中
            List<ReturnVO> returnVOList = projectVO.getReturnVOList();
            // 判断projectVO中的returnVOList是否有效，无效的话初始化一个新的
            if (returnVOList == null || returnVOList.size() == 0){
                returnVOList = new ArrayList<>();
                projectVO.setReturnVOList(returnVOList);
            }
            returnVOList.add(returnVO);
            // 重新存入session
            session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT,projectVO);

            return ResultEntity.successWithOutData();
        }catch (Exception e){
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

    /**
     * 单独上传回报页面的图片到oss服务的方法
     * @param returnPicture 回报页面需要上传的图片
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/create/upload/return/picture.json")
    public ResultEntity<String> uploadReturnPicture(
            @RequestParam("returnPicture") MultipartFile returnPicture) throws IOException {
        ResultEntity<String> returnPicResultEntity = CrowdUtil.uploadFileToOss(
                ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                returnPicture.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                returnPicture.getOriginalFilename());

        return returnPicResultEntity;
    }


    /**
     *  提交项目信息的方法
     * @param projectVO 收集除了上传图片之外的普通信息
     * @param headerPicture 头图文件
     * @param detailPictureList 详情图文件
     * @param session 用来将部分数据的projectVO对象存入session域中
     * @param modelMap 提交失败后，返回上级页面，携带提示消息
     * @return 提交成功后的跳转地址
     */
    @RequestMapping("/create/project/information")
    public String saveProjectBasicInfo(ProjectVO projectVO, MultipartFile headerPicture,
                                       List<MultipartFile> detailPictureList, HttpSession session,
                                       ModelMap modelMap) throws IOException {

        boolean headerPicIsEmpty = headerPicture.isEmpty();
        if (headerPicIsEmpty){
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_HEADER_PICTURE_EMPTY);
            return "project-launch";
        }

        if (!headerPicIsEmpty){
            // 上传头图到oss服务器
            ResultEntity<String> uploadFileToOssResult = CrowdUtil.uploadFileToOss(
                    ossProperties.getEndPoint(),
                    ossProperties.getAccessKeyId(),
                    ossProperties.getAccessKeySecret(),
                    headerPicture.getInputStream(),
                    ossProperties.getBucketName(),
                    ossProperties.getBucketDomain(),
                    headerPicture.getOriginalFilename());
            // 判断上传是否成功
            String result = uploadFileToOssResult.getResult();
            if (ResultEntity.SUCCESS.equals(result)){
                // 取出访问地址
                String headPicOssPath = uploadFileToOssResult.getData();
                // 存入projectVO
                projectVO.setHeaderPicturePath(headPicOssPath);
            }else {
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_OSS_UPLOAD_FAIL);
                return "project-launch";
            }
        }

        if (detailPictureList == null || detailPictureList.size() == 0){
            // 检查页面上传的细节图是否是空的
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_DETAIL_PICTURE_EMPTY);
            return "project-launch";
        }

        // 建立集合保存细节图
        List<String> detailPicturePathList = new ArrayList<>();
        // 遍历详情图片集合
        for(MultipartFile detailPic : detailPictureList){
            // 不为空，就上传细节图
            if (!detailPic.isEmpty()){
                ResultEntity<String> detailPicToOssResult = CrowdUtil.uploadFileToOss(
                        ossProperties.getEndPoint(),
                        ossProperties.getAccessKeyId(),
                        ossProperties.getAccessKeySecret(),
                        detailPic.getInputStream(),
                        ossProperties.getBucketName(),
                        ossProperties.getBucketDomain(),
                        detailPic.getOriginalFilename());
                // 上传结果成功
                if(ResultEntity.SUCCESS.equals(detailPicToOssResult.getResult())){
                    String detailPicOssPath = detailPicToOssResult.getData();
                    // 详情图片访问路径存入集合
                    detailPicturePathList.add(detailPicOssPath);
                }else {
                    continue;
                }
            }
        }
        // 详情图地址集合存入projectVO对象
        projectVO.setDetailPicturePathList(detailPicturePathList);

        // projectVO对象存入session域中
        session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT,projectVO);

        // 完整访问路径，从zuul重定向到下一个页面
        // 保证session的一致性
        return "redirect:http://localhost/project/return/info/page";
    }
}
